﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace IWMAG.Scripting.Interpreter {
    class ScriptEngine {
        protected List<Task> Pool = new List<Task>();
        protected List<Task> NewPool = new List<Task>();

        public bool HasOpenContexts {
            get {
                return Pool.Count + NewPool.Count != 0;
            }
        }

        public void Start(Func<ScriptEngine, IEnumerable<int>> f) {
            IEnumerator<int> p = f(this).GetEnumerator();
            NewPool.Add(new Task(-1337, p));
        }

        protected int Resume(IEnumerator<int> a, bool first = false) {
            if (!first) {
                if (!a.MoveNext()) {
                    return -9999;
                }
            }

            return a.Current;
        }

        public void Update(float duration) {
            if (NewPool.Count != 0) {
                foreach (Task newtask in NewPool) {
                    Pool.Add(newtask);
                }
                NewPool.Clear();
            }

            bool[] finished = new bool[Pool.Count];
            int j = 0;
            foreach (Task context in Pool) {
                finished[j] = false;
                bool first = context.Waiting == -1337;
                context.Waiting -= (int) (duration * 1000);
                if (context.Waiting <= 0) {
                    context.Waiting = Resume(context.Ptr, first);
                    finished[j] = context.Waiting == -9999;
                }
                j++;
            }
            for (int i = Pool.Count - 1; i >= 0; i--) {
                if (finished[i]) {
                    Pool.RemoveAt(i);
                }
            }
        }
    }
}
